import React, { useEffect, useState, useRef } from 'react'
import axios from 'axios'
// import { Table, Button, Tooltip, Space, message, Popconfirm, Popover, Switch, Modal, Form, Input, Select } from 'antd'
import { Table, Button, Tooltip, Space, message, Popconfirm, Switch, Modal } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import UserForm from '../../../components/user-manage/UserForm';

export default function UserList() {
    const [dataSource, setDataSource] = useState([])
    // 添加用户对话框状态
    const [isAddVisible, setisAddVisible] = useState(false)
    // 更新用户对话框状态
    const [isUpdateVisible, setisUpdateVisible] = useState(false)
    // 区域列表
    const [regionList, setregionList] = useState([])
    // 角色列表
    const [roleList, setroleList] = useState([])
    // 是否根据角色禁用区域状态
    const [isUpdateDisable, setUpdateDisable] = useState(false)
    // 表单Ref
    const addForm = useRef(null)
    // 更新用户表单Ref
    const updateForm = useRef(null)
    // 更新用户当前项
    const [currentUpdate, setCurrentUpdate] = useState([])
    // 获取当前用户token信息
    const {roleId, region, username} = JSON.parse(localStorage.getItem("token"))

    // 请求用户数据
    useEffect(() => {
        // 定义角色信息
        const roleObj ={
            "1": "superadmin",
            "2": "admin",
            "3": "editor",

        }
        // 根据用户权限获取用户列表
        axios.get('/users?_expand=role').then(res => {
            // console.log(res.data);
            const list = res.data
            setDataSource(roleObj[roleId] === "superadmin" ? list : [
                ...list.filter(item=>item.username === username),
                ...list.filter(item=>item.region === region && roleObj[item.roleId]==="editor")
            ])
        })
    }, [region, username, roleId])
    // 请求权限列表
    useEffect(() => {
        axios.get('/regions').then(res => {
            // console.log(res.data, 'regions');
            setregionList(res.data)
        })
    }, [])
    // 请求角色
    useEffect(() => {
        axios.get('/roles').then(res => {
            // console.log(res.data, 'roles');
            let list = res.data.map(item => {
                return {
                    ...item,
                    value: item.id,
                    label: item.roleName
                }
            })
            setroleList([...list])
        })
    }, [])
    // 用户状态发生变化
    const userStateChange = (item) => {
        // console.log(item)
        item.roleState = !item.roleState
        setDataSource([...dataSource])

        axios.patch(`/users/${item.id}`, {
            roleState: item.roleState
        })
    }
    // 表格每列分类配置
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters: [
                ...regionList.map(item =>({
                    text: item.title,
                    value: item.value
                })),
                {
                    text: "全球",
                    value: ""
                }
            ],
            onFilter: (value, item) => {
                return item.region === value
            },
            render: (region) => {
                return <b>{region === "" ? '全球' : region}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => {
                return role.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'username',
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item) => {
                return <div>
                    <Switch checked={roleState} disabled={item.default} onChange={() => userStateChange(item)} />
                </div>
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Space size="2">
                        <Popconfirm
                            title="删除用户"
                            description="是否永久删除该用户？"
                            onConfirm={() => confirm(item)}
                            onCancel={cancel}
                            okText="确认"
                            cancelText="取消"
                        >
                            <Tooltip title="删除" mouseLeaveDelay={0}>
                                <Button danger shape="circle" icon={<DeleteOutlined />} style={{ marginRight: '10px' }} disabled={item.default}/>
                            </Tooltip>
                        </Popconfirm>
                        <Tooltip title="修改用户信息" mouseLeaveDelay={0}>
                            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>clickUpdate(item)} disabled={item.default}/>
                        </Tooltip>
                    </Space>
                </div>
            }
        },
    ];
    // 点击确认删除用户
    const confirm = (item) => {
        // console.log(item);
        setDataSource(dataSource.filter(data => data.id !== item.id))
        axios.delete(`/users/${item.id}`)
        message.success('删除成功');
    };
    // 取消删除用户
    const cancel = (e) => {
        // console.log(e);
        message.info('已取消删除');
    };
    // 点击确认添加用户
    const addFormOK = (item) => {
        console.log(item);
        addForm.current.validateFields().then(value => {
            console.log(value);
            axios.post(`/users`, {
                ...value,
                "roleState": true,
                "default": false,
            }).then(res => {
                console.log(res.data);
                setDataSource([...dataSource, {
                    ...res.data,
                    role: roleList.filter(item => item.id === value.roleId)[0]
                }])
            }).catch(err => err)
            // 清空表单信息
            addForm.current.resetFields()
        })
        setisAddVisible(false)
        message.success('添加用户成功');

    }
    // 点击更新用户信息
    const clickUpdate = async (item) => {
        // console.log(item);
        await
            setisUpdateVisible(true)
            if(item.roleId === 1) {
                setUpdateDisable(true)
            }else{
                setUpdateDisable(false)
            }
            updateForm.current.setFieldsValue(item)
            setCurrentUpdate(item)
    }
    // 确定更新用户信息
    const updateFormOK = () => {
        updateForm.current.validateFields().then(value => {
            setDataSource(dataSource.map(item => {
                // console.log(currentUpdate.id,'current.id');
                if(item.id === currentUpdate.id) {
                    return {
                        ...item,
                        ...value,
                        role: roleList.filter(data=>data.id===value.roleId)[0]
                    }
                }
                return item
            }))
            axios.patch(`/users/${currentUpdate.id}`, value)
            message.success('修改成功');
            setisUpdateVisible(false)
        })
        // console.log(updateForm);
    }
    return (
        <div>
            <Button type="primary" style={{ marginBottom: '25px' }} onClick={() => {
                setisAddVisible(true)
            }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 7
            }} rowKey={(item) => item.id} />
            <Modal
                open={isAddVisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={() => {
                    setisAddVisible(false)
                    message.info('已取消添加');
                }}
                onOk={() => addFormOK()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
            </Modal>
            <Modal
                open={isUpdateVisible}
                title="修改用户"
                okText="确定"
                cancelText="取消"
                onCancel={async () => {
                    await
                    setisUpdateVisible(false)
                    // console.log('listDisable:',isUpdateDisable,!isUpdateDisable);
                    // setUpdateDisable(!isUpdateDisable)
                    message.info('已取消修改');
                }}
                onOk={() => updateFormOK()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisable={isUpdateDisable} isUpdate={true}></UserForm>
            </Modal>
        </div>
    )
}
